package com.lxw.manage_cms.service;


import com.lxw.framework.domain.cms.CmsPage;
import com.lxw.framework.domain.cms.CmsTemplate;
import com.lxw.framework.exception.ExceptionCast;
import com.lxw.framework.model.response.CommonCode;
import com.lxw.manage_cms.dao.CmsTemplateDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CmsTemplateServiceImpl implements ICmsTemplateService{

    @Autowired
    CmsTemplateDao cmsTemplateDao;

    @Override
    public List<CmsTemplate> findTemplate(String siteId, String tempName) {

/*
        ExampleMatcher.GenericPropertyMatcher of =
                ExampleMatcher.GenericPropertyMatcher.of(ExampleMatcher.StringMatcher.CONTAINING);
*/

        //条件匹配器
        ExampleMatcher exampleMatcher = ExampleMatcher.matching();
        exampleMatcher = exampleMatcher.withMatcher("templateName",
                ExampleMatcher.GenericPropertyMatchers.contains());

        //封装条件对象
        CmsTemplate cmsTemplate = new CmsTemplate();
        cmsTemplate.setSiteId(siteId);
        cmsTemplate.setTemplateName(tempName);
        Example<CmsTemplate> of = Example.of(cmsTemplate, exampleMatcher);


        List<CmsTemplate> all = cmsTemplateDao.findAll(of);

        return all;
    }

    @Override
    public void addTemplate(CmsTemplate cmsTemplate) {
        //非空校验
        if (cmsTemplate.getTemplateName() == null || "".equals(cmsTemplate.getTemplateName())){
            throw new RuntimeException("参数为空");
        }
        if (cmsTemplate.getSiteId() == null || "".equals(cmsTemplate.getSiteId())){
            throw new RuntimeException("参数为空");
        }
        if (cmsTemplate.getTemplateFileId() == null || "".equals(cmsTemplate.getTemplateFileId())){
            throw new RuntimeException("参数为空");
        }

        cmsTemplateDao.save(cmsTemplate);
    }

    @Override
    public List<CmsTemplate> findTemplateAll() {

        List<CmsTemplate> all = cmsTemplateDao.findAll();
        return all;
    }

    @Override
    public CmsTemplate findTemplateById(String templateId) {
        Optional<CmsTemplate> byId = cmsTemplateDao.findById(templateId);
        if (!byId.isPresent()){
            ExceptionCast.cast(CommonCode.FAIL);
        }

        return byId.get();
    }
}
